import moment from 'moment'

export function parseTime(time, format) {
  format = format || 'YYYY-MM-DD HH:mm'
  if (!time) {
    return ''
  }
  return moment(time).format(format)
}

export const findDict = (dict, current) => {
  return dict.find(e => e.key === current) || {}
}
export const isValid = val => {
  const invalidMap = ['', null, undefined]
  return !invalidMap.includes(val)
}
export const isValidArray = arr => {
  if (!isValid(arr)) {
    return false
  }
  if (arr.length > 0) {
    return true
  }
  return false
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}

/**
 * 合并对象,区别于 {...a, ...b} ,b中项为undefined不会覆盖a
 *
 * @export
 * @param {*} [target={}] 当前值
 * @param {*} [mixin={}] 补充值
 * @returns 合并后的新对象
 */
export function extendsObj(target = {}, mixin = {}) {
  Object.keys(mixin).forEach(key => {
    const currentMixin = mixin[key]
    if (currentMixin !== undefined) {
      target[key] = currentMixin
    }
  })
  return target
}

/**
 * 通过值获取数据
 *
 * @export
 * @param {*} [arr=[]] 数组
 * @param {*} val 值
 * @param {string} [key='key'] 对应的 key
 * @returns
 */
export function byKeyGetItem(list = [], val, key = 'key') {
  let result = { value: '' }
  list.map(item => {
    if (item[key] === val) {
      result = item
    }
  })
  return result
}

const _findChild = (root, childrenNodes, key, parentKey) => {
  if (childrenNodes.length <= 0) return false
  const newChildrenNodes = []
  const childrenNodeMap = JSON.parse(JSON.stringify(childrenNodes))
  childrenNodes.map((child, index) => {
    if (root[key] === child[parentKey]) {
      root.children = [...(root.children || []), child]
      childrenNodeMap.splice(index, 1)
      _findChild(child, childrenNodeMap, key, parentKey)
    } else {
      newChildrenNodes.push(child)
    }
  })
  childrenNodes = newChildrenNodes
  return false
}

/**
 * 获得树形结构数据
 *
 * @export
 * @param {*} [list=[]] 数组
 * @param {string} [key='id'] 用于判断的 key
 * @param {string} [parentKey='parentOrgId'] 用于判断的 parentKey
 * @returns
 */
export function createTreeList(
  list = [],
  key = 'id',
  parentKey = 'parentOrgId'
) {
  let roots = []
  let level = 0
  while (!roots.length) {
    level++
    roots = list.filter(item => item.level === level)
  }
  const childrenNodes = list.filter(item => item.level !== level)
  roots.map(root => {
    _findChild(root, childrenNodes, key, parentKey)
  })
  return roots
}

/**
 * 通过身份证号码 获取生日 性别和年龄
 *
 * @export
 * @param {string} [idCard='']
 */
export function getBirthSexByIDCard(idCard = '') {
  const result = {}
  const sexArr = ['女', '男']
  if (idCard.length === 15) {
    let birthStr = idCard.charAt(6) + idCard.charAt(7)
    if (+birthStr < 10) {
      birthStr = '20' + birthStr
    } else {
      birthStr = '19' + birthStr
    }
    result.birth =
      birthStr +
      '-' +
      idCard.charAt(8) +
      idCard.charAt(9) +
      '-' +
      idCard.charAt(10) +
      idCard.charAt(11)
    result.sex = sexArr[idCard.charAt(14) % 2]
  } else if (idCard.length === 18) {
    result.birth =
      idCard.substring(6, 10) +
      '-' +
      idCard.substring(10, 12) +
      '-' +
      idCard.substring(12, 14)
    result.sex = sexArr[idCard.charAt(16) % 2]
  }
  return result
}

/**
 * 数组去重
 *
 * @export
 * @param {*} arr { 数组 }
 * @returns
 */
export function arrayUnique(arr) {
  return Array.from(new Set(arr))
}

/**
 * blob 导出
 *
 * @export
 * @param {*} blob
 * @param {*} headers
 */
export function blobDownload(blob, headers) {
  const a = window.document.createElement('a')
  const downUrl = window.URL.createObjectURL(blob) // 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上)
  const filename = headers['content-disposition']
    // .get('content-disposition')
    .split('filename=')[1]
    .replace(/"/g, '')
    .replace(/'/g, '')
  a.href = downUrl
  a.download = decodeURI(filename)

  const evt = document.createEvent('MouseEvents')
  evt.initEvent('click', true, true)
  a.dispatchEvent(evt)
  window.URL.revokeObjectURL(downUrl)
}

// 处理树形结构
// 结构 id: "1", name: "顺碧区域", parentDeptId: "0", type: 2
export function formatTree(res, str = '') {
  const obj_list = []
  res.forEach(item => {
    if (item.parentDeptId === str + '0') {
      obj_list.push({ ...item, children: [] })
    } else {
      // 处理第二层
      obj_list.forEach(twoInner => {
        if (item.parentDeptId === twoInner.id) {
          twoInner.children.push({ ...item, children: [] })
        }
        // 处理第三层
        if (twoInner.children !== []) {
          twoInner.children.forEach(threeInner => {
            if (item.parentDeptId === threeInner.id) {
              threeInner.children.push({ ...item, children: [] })
            }
            // 处理第四层
            if (threeInner.children !== []) {
              threeInner.children.forEach(fourInner => {
                if (item.parentDeptId === fourInner.id) {
                  fourInner.children.push({ ...item, children: [] })
                }
                // 处理第五层
                if (fourInner.children !== []) {
                  fourInner.children.forEach(fiveInner => {
                    if (item.parentDeptId === fiveInner.id) {
                      fiveInner.children.push({ ...item, children: [] })
                    }
                  })
                }
              })
            }
          })
        }
      })
    }
  })
  return obj_list
}

export const transTreeData = option => {
  const defaultOption = {
    list: [],
    rootId: 0, // 最外层的parentId
    filterLast: () => true,
    props: {
      idKey: 'id',
      pidKey: 'pid',
      childKey: 'children'
    },
    appends: []
  }
  const props = { ...defaultOption.props, ...option.props }
  option = { ...defaultOption, ...option, props }
  const findChildren = pid => {
    const result = []
    option.list.forEach(e => {
      if (e[option.props.pidKey] === pid) {
        const _children = findChildren(e[option.props.idKey])
        e[option.props.childKey] = _children
        e._childCount = _children.length
        e._last = _children.length === 0
        option.appends.forEach(ee => {
          const value = ee.value ? ee.value : e[ee.in]
          e[ee.out] = value
        })

        result.push(e)
      }
    })
    return result
  }
  return findChildren(option.rootId)
}

